<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理系统 - zut Chat</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f5f5;
            color: #333;
        }

        .header {
            background: linear-gradient(135deg, #07c160 0%, #06ae56 100%);
            color: white;
            padding: 1rem 2rem;
            box-shadow: 0 2px 10px rgba(7, 193, 96, 0.2);
            position: relative;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h1 {
            font-size: 1.5rem;
            font-weight: 600;
        }
        
        .header-right {
            display: flex;
            align-items: center;
            gap: 16px;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
        }
        
        .logout-btn {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 8px 16px;
            border-radius: 20px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s ease;
        }
        
        .logout-btn:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: translateY(-1px);
        }

        .container {
            max-width: 1200px;
            margin: 2rem auto;
            padding: 0 1rem;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .stat-card {
            background: white;
            padding: 1.5rem;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(7, 193, 96, 0.1);
            text-align: center;
            border: 1px solid rgba(7, 193, 96, 0.1);
            transition: all 0.3s ease;
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 30px rgba(7, 193, 96, 0.15);
        }

        .stat-card .icon {
            font-size: 2rem;
            margin-bottom: 0.5rem;
            color: #07c160;
        }

        .stat-card .number {
            font-size: 2rem;
            font-weight: bold;
            color: #333;
        }

        .stat-card .label {
            color: #666;
            font-size: 0.9rem;
        }

        .tabs {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            border: 1px solid rgba(7, 193, 96, 0.1);
        }

        .tab-buttons {
            display: flex;
            border-bottom: 1px solid #e0e0e0;
        }

        .tab-button {
            flex: 1;
            padding: 1rem;
            background: none;
            border: none;
            cursor: pointer;
            font-size: 1rem;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            color: #666;
        }
        
        .tab-button:hover:not(.active) {
            background: rgba(7, 193, 96, 0.05);
            color: #07c160;
        }

        .tab-button.active {
            background: linear-gradient(135deg, #07c160, #06ae56);
            color: white;
            box-shadow: 0 2px 8px rgba(7, 193, 96, 0.3);
        }

        .tab-content {
            display: none;
            padding: 1.5rem;
        }

        .tab-content.active {
            display: block;
        }

        .search-bar {
            display: flex;
            gap: 1rem;
            margin-bottom: 1rem;
            flex-wrap: wrap;
        }

        .search-bar input, .search-bar select {
            padding: 0.75rem;
            border: 2px solid #e7e7e7;
            border-radius: 8px;
            font-size: 0.9rem;
            transition: all 0.2s ease;
        }
        
        .search-bar input:focus, .search-bar select:focus {
            outline: none;
            border-color: #07c160;
            box-shadow: 0 0 0 3px rgba(7, 193, 96, 0.1);
        }

        .search-bar button {
            padding: 0.75rem 1.5rem;
            background: linear-gradient(135deg, #07c160, #06ae56);
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
            box-shadow: 0 2px 8px rgba(7, 193, 96, 0.3);
        }

        .search-bar button:hover {
            background: linear-gradient(135deg, #06ae56, #07c160);
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(7, 193, 96, 0.4);
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1rem;
        }

        .table th, .table td {
            padding: 0.75rem;
            text-align: left;
            border-bottom: 1px solid #e0e0e0;
        }

        .table th {
            background: #f8f9fa;
            font-weight: 600;
        }

        .table tr:hover {
            background: #f8f9fa;
        }

        .badge {
            padding: 0.25rem 0.5rem;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .badge.admin {
            background: #ffd700;
            color: #333;
        }

        .badge.normal {
            background: #e0e0e0;
            color: #666;
        }

        .badge.online {
            background: #07c160;
            color: white;
        }

        .badge.offline {
            background: #f44336;
            color: white;
        }

        .action-btn {
            padding: 0.4rem 0.8rem;
            margin: 0 0.25rem;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.75rem;
            font-weight: 500;
            transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
        }

        .action-btn.primary {
            background: linear-gradient(135deg, #07c160, #06ae56);
            color: white;
            box-shadow: 0 2px 4px rgba(7, 193, 96, 0.3);
        }

        .action-btn.danger {
            background: linear-gradient(135deg, #ff6b6b, #ee5a52);
            color: white;
            box-shadow: 0 2px 4px rgba(255, 107, 107, 0.3);
        }

        .action-btn.success {
            background: linear-gradient(135deg, #07c160, #06ae56);
            color: white;
            box-shadow: 0 2px 4px rgba(7, 193, 96, 0.3);
        }

        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .action-btn.primary:hover {
            box-shadow: 0 4px 12px rgba(7, 193, 96, 0.4);
        }

        .action-btn.danger:hover {
            box-shadow: 0 4px 12px rgba(255, 107, 107, 0.4);
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 0.5rem;
            margin-top: 1rem;
        }

        .pagination button {
            padding: 0.6rem 1.2rem;
            border: 2px solid #e7e7e7;
            background: white;
            cursor: pointer;
            border-radius: 8px;
            transition: all 0.2s ease;
            font-weight: 500;
            color: #666;
        }

        .pagination button:hover:not(:disabled) {
            background: #07c160;
            color: white;
            border-color: #07c160;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(7, 193, 96, 0.3);
        }

        .pagination button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .loading {
            text-align: center;
            padding: 2rem;
            color: #666;
        }

        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 1rem 1.5rem;
            border-radius: 5px;
            color: white;
            z-index: 1000;
            opacity: 0;
            transform: translateX(100%);
            transition: all 0.3s ease;
        }

        .notification.show {
            opacity: 1;
            transform: translateX(0);
        }

        .notification.success {
            background: #07c160;
        }

        .notification.error {
            background: #f44336;
        }

        @media (max-width: 768px) {
            .container {
                padding: 0 0.5rem;
            }
            
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .tab-buttons {
                flex-direction: column;
            }
            
            .search-bar {
                flex-direction: column;
            }
            
            .table {
                font-size: 0.8rem;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1><i class="fas fa-shield-alt"></i> zut Chat 后台管理系统</h1>
        <div class="header-right">
            <div class="user-info">
                <i class="fas fa-user-circle"></i>
                <span id="currentUser">加载中...</span>
            </div>
            <button class="logout-btn" onclick="logout()">
                <i class="fas fa-sign-out-alt"></i> 退出
            </button>
        </div>
    </div>

    <div class="container">
        <!-- 统计信息 -->
        <div class="stats-grid" id="statsGrid">
            <div class="stat-card">
                <div class="icon"><i class="fas fa-users"></i></div>
                <div class="number" id="totalUsers">-</div>
                <div class="label">总用户数</div>
            </div>
            <div class="stat-card">
                <div class="icon"><i class="fas fa-user-check"></i></div>
                <div class="number" id="onlineUsers">-</div>
                <div class="label">在线用户</div>
            </div>
            <div class="stat-card">
                <div class="icon"><i class="fas fa-comments"></i></div>
                <div class="number" id="totalMessages">-</div>
                <div class="label">总消息数</div>
            </div>
            <div class="stat-card">
                <div class="icon"><i class="fas fa-calendar-day"></i></div>
                <div class="number" id="todayMessages">-</div>
                <div class="label">今日消息</div>
            </div>
            <div class="stat-card">
                <div class="icon"><i class="fas fa-user-shield"></i></div>
                <div class="number" id="adminCount">-</div>
                <div class="label">管理员数</div>
            </div>
        </div>

        <!-- 功能快捷入口 -->
        <div class="stats-grid" style="margin-bottom: 2rem;">
            <a href="/bot-management.html" class="stat-card" style="text-decoration: none; color: inherit;">
                <div class="icon"><i class="fas fa-robot"></i></div>
                <div class="number">🤖</div>
                <div class="label">机器人管理</div>
            </a>
            <a href="/rate-limit-management.html" class="stat-card" style="text-decoration: none; color: inherit;">
                <div class="icon"><i class="fas fa-tachometer-alt"></i></div>
                <div class="number">⚡</div>
                <div class="label">频率限制</div>
            </a>
            <div class="stat-card" onclick="showBannedUsers()" style="cursor: pointer;">
                <div class="icon"><i class="fas fa-user-slash"></i></div>
                <div class="number" id="bannedUsersCount">-</div>
                <div class="label">禁言用户</div>
            </div>
            <div class="stat-card" onclick="window.open('/index.html', '_blank')" style="cursor: pointer;">
                <div class="icon"><i class="fas fa-comments"></i></div>
                <div class="number">💬</div>
                <div class="label">进入聊天室</div>
            </div>
        </div>

        <!-- 选项卡 -->
        <div class="tabs">
            <div class="tab-buttons">
                <button class="tab-button active" data-tab="users">
                    <i class="fas fa-users"></i> 用户管理
                </button>
                <button class="tab-button" data-tab="messages">
                    <i class="fas fa-comments"></i> 消息管理
                </button>
                <button class="tab-button" data-tab="banned">
                    <i class="fas fa-user-slash"></i> 禁言管理
                </button>
            </div>

            <!-- 用户管理 -->
            <div class="tab-content active" id="users">
                <div class="search-bar">
                    <input type="text" id="userSearch" placeholder="搜索用户昵称...">
                    <select id="userTypeFilter">
                        <option value="">所有类型</option>
                        <option value="NORMAL">普通用户</option>
                        <option value="ADMIN">管理员</option>
                    </select>
                    <button onclick="searchUsers()">搜索</button>
                    <button onclick="loadUsers()">刷新</button>
                </div>

                <div id="usersLoading" class="loading" style="display: none;">
                    <i class="fas fa-spinner fa-spin"></i> 加载中...
                </div>

                <table class="table" id="usersTable" style="display: none;">
                    <thead>
                        <tr>
                            <th>昵称</th>
                            <th>用户类型</th>
                            <th>状态</th>
                            <th>创建时间</th>
                            <th>最后活跃</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="usersTableBody">
                    </tbody>
                </table>

                <div class="pagination" id="usersPagination" style="display: none;">
                </div>
            </div>

            <!-- 消息管理 -->
            <div class="tab-content" id="messages">
                <div class="search-bar">
                    <input type="text" id="messageSearch" placeholder="搜索发送者昵称...">
                    <select id="messageTypeFilter">
                        <option value="">所有类型</option>
                        <option value="TEXT">文本消息</option>
                        <option value="IMAGE">图片消息</option>
                        <option value="SYSTEM">系统消息</option>
                        <option value="JOIN">加入消息</option>
                        <option value="LEAVE">离开消息</option>
                    </select>
                    <button onclick="searchMessages()">搜索</button>
                    <button onclick="loadMessages()">刷新</button>
                </div>

                <div id="messagesLoading" class="loading" style="display: none;">
                    <i class="fas fa-spinner fa-spin"></i> 加载中...
                </div>

                <table class="table" id="messagesTable" style="display: none;">
                    <thead>
                        <tr>
                            <th>发送者</th>
                            <th>消息类型</th>
                            <th>内容</th>
                            <th>发送时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="messagesTableBody">
                    </tbody>
                </table>

                <div class="pagination" id="messagesPagination" style="display: none;">
                </div>
            </div>

            <!-- 禁言管理 -->
            <div class="tab-content" id="banned">
                <div class="search-bar">
                    <input type="text" id="bannedUserSearch" placeholder="搜索被禁言用户昵称...">
                    <button onclick="searchBannedUsers()">搜索</button>
                    <button onclick="loadBannedUsers()">刷新</button>
                </div>

                <div id="bannedUsersLoading" class="loading" style="display: none;">
                    <i class="fas fa-spinner fa-spin"></i> 加载中...
                </div>

                <table class="table" id="bannedUsersTable" style="display: none;">
                    <thead>
                        <tr>
                            <th>昵称</th>
                            <th>禁言原因</th>
                            <th>禁言时间</th>
                            <th>到期时间</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="bannedUsersTableBody">
                    </tbody>
                </table>

                <div id="noBannedUsers" style="display: none; text-align: center; padding: 40px; color: #666;">
                    <i class="fas fa-user-check" style="font-size: 3em; margin-bottom: 20px;"></i>
                    <h3>暂无被禁言的用户</h3>
                    <p>所有用户目前都可以正常聊天</p>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentUsersPage = 0;
        let currentMessagesPage = 0;
        const pageSize = 20;

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
        });
        
        // 检查登录状态
        async function checkAuth() {
            try {
                const response = await fetch('/api/auth/check');
                const data = await response.json();
                
                if (data.success) {
                    document.getElementById('currentUser').textContent = data.user.realName || data.user.username;
                    setupTabs();
                    loadStats();
                    loadUsers();
                } else {
                    // 未登录，跳转到登录页面
                    window.location.href = '/admin-login';
                }
            } catch (error) {
                console.error('检查登录状态失败:', error);
                window.location.href = '/admin-login';
            }
        }
        
        // 退出登录
        async function logout() {
            if (confirm('确定要退出登录吗？')) {
                try {
                    const response = await fetch('/api/auth/logout', {
                        method: 'POST'
                    });
                    const data = await response.json();
                    
                    if (data.success) {
                        window.location.href = '/admin-login';
                    } else {
                        alert('退出失败，请重试');
                    }
                } catch (error) {
                    console.error('退出登录失败:', error);
                    alert('网络错误，请重试');
                }
            }
        }

        // 设置选项卡功能
        function setupTabs() {
            const tabButtons = document.querySelectorAll('.tab-button');
            const tabContents = document.querySelectorAll('.tab-content');

            tabButtons.forEach(button => {
                button.addEventListener('click', () => {
                    const tabName = button.dataset.tab;
                    
                    // 更新按钮状态
                    tabButtons.forEach(btn => btn.classList.remove('active'));
                    button.classList.add('active');
                    
                    // 更新内容显示
                    tabContents.forEach(content => content.classList.remove('active'));
                    document.getElementById(tabName).classList.add('active');
                    
                    // 加载对应数据
                    if (tabName === 'users') {
                        loadUsers();
                    } else if (tabName === 'messages') {
                        loadMessages();
                    } else if (tabName === 'banned') {
                        loadBannedUsers();
                    }
                });
            });
        }

        // 加载统计信息
        function loadStats() {
            fetch('/api/backend/stats')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const stats = data.data;
                        document.getElementById('totalUsers').textContent = stats.totalUsers;
                        document.getElementById('onlineUsers').textContent = stats.onlineUsers;
                        document.getElementById('totalMessages').textContent = stats.totalMessages;
                        document.getElementById('todayMessages').textContent = stats.todayMessages;
                        document.getElementById('adminCount').textContent = stats.adminCount;
                    }
                })
                .catch(error => {
                    console.error('加载统计信息失败:', error);
                });
        }

        // 加载用户列表
        function loadUsers(page = 0) {
            currentUsersPage = page;
            const loading = document.getElementById('usersLoading');
            const table = document.getElementById('usersTable');
            
            loading.style.display = 'block';
            table.style.display = 'none';

            const nickname = document.getElementById('userSearch').value;
            const userType = document.getElementById('userTypeFilter').value;
            
            let url = `/api/backend/users?page=${page}&size=${pageSize}`;
            if (nickname) url += `&nickname=${encodeURIComponent(nickname)}`;
            if (userType) url += `&userType=${userType}`;

            fetch(url)
                .then(response => response.json())
                .then(data => {
                    loading.style.display = 'none';
                    
                    if (data.success) {
                        displayUsers(data.data);
                        updateUsersPagination(data.total, page);
                        table.style.display = 'table';
                    } else {
                        showNotification('加载用户失败: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    showNotification('加载用户失败: ' + error.message, 'error');
                });
        }

        // 显示用户列表
        function displayUsers(users) {
            const tbody = document.getElementById('usersTableBody');
            tbody.innerHTML = '';

            users.forEach(user => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${user.nickname}</td>
                    <td><span class="badge ${user.userType.toLowerCase()}">${user.userType === 'ADMIN' ? '管理员' : '普通用户'}</span></td>
                    <td><span class="badge ${user.online ? 'online' : 'offline'}">${user.online ? '在线' : '离线'}</span></td>
                    <td>${new Date(user.createTime).toLocaleString()}</td>
                    <td>${new Date(user.lastActiveTime).toLocaleString()}</td>
                    <td>
                        ${user.userType !== 'ADMIN' ? `
                            <button class="action-btn success" onclick="setAdmin('${user.sessionId}', '${user.nickname}')">
                                <i class="fas fa-user-shield"></i> 设为管理员
                            </button>
                        ` : `
                            <button class="action-btn primary" onclick="removeAdmin('${user.sessionId}', '${user.nickname}')">
                                <i class="fas fa-user-minus"></i> 取消管理员
                            </button>
                        `}
                        <button class="action-btn danger" onclick="deleteUser('${user.sessionId}', '${user.nickname}')">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </td>
                `;
                tbody.appendChild(tr);
            });
        }

        // 搜索用户
        function searchUsers() {
            loadUsers(0);
        }

        // 设置管理员
        function setAdmin(sessionId, nickname) {
            if (!confirm(`确定要将用户 "${nickname}" 设置为管理员吗？`)) {
                return;
            }

            fetch(`/api/backend/users/${sessionId}/set-admin`, {
                method: 'POST'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showNotification(data.message, 'success');
                        loadUsers(currentUsersPage);
                        loadStats();
                    } else {
                        showNotification(data.message, 'error');
                    }
                })
                .catch(error => {
                    showNotification('操作失败: ' + error.message, 'error');
                });
        }

        // 取消管理员
        function removeAdmin(sessionId, nickname) {
            if (!confirm(`确定要取消用户 "${nickname}" 的管理员权限吗？`)) {
                return;
            }

            fetch(`/api/backend/users/${sessionId}/remove-admin`, {
                method: 'POST'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showNotification(data.message, 'success');
                        loadUsers(currentUsersPage);
                        loadStats();
                    } else {
                        showNotification(data.message, 'error');
                    }
                })
                .catch(error => {
                    showNotification('操作失败: ' + error.message, 'error');
                });
        }

        // 删除用户
        function deleteUser(sessionId, nickname) {
            if (!confirm(`确定要删除用户 "${nickname}" 吗？此操作不可恢复！`)) {
                return;
            }

            fetch(`/api/backend/users/${sessionId}`, {
                method: 'DELETE'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showNotification(data.message, 'success');
                        loadUsers(currentUsersPage);
                        loadStats();
                    } else {
                        showNotification(data.message, 'error');
                    }
                })
                .catch(error => {
                    showNotification('删除失败: ' + error.message, 'error');
                });
        }

        // 更新用户分页
        function updateUsersPagination(total, currentPage) {
            const pagination = document.getElementById('usersPagination');
            const totalPages = Math.ceil(total / pageSize);
            
            if (totalPages <= 1) {
                pagination.style.display = 'none';
                return;
            }
            
            pagination.style.display = 'flex';
            pagination.innerHTML = `
                <button ${currentPage === 0 ? 'disabled' : ''} onclick="loadUsers(${currentPage - 1})">
                    <i class="fas fa-chevron-left"></i> 上一页
                </button>
                <span>第 ${currentPage + 1} 页 / 共 ${totalPages} 页</span>
                <button ${currentPage >= totalPages - 1 ? 'disabled' : ''} onclick="loadUsers(${currentPage + 1})">
                    下一页 <i class="fas fa-chevron-right"></i>
                </button>
            `;
        }

        // 加载消息列表
        function loadMessages(page = 0) {
            currentMessagesPage = page;
            const loading = document.getElementById('messagesLoading');
            const table = document.getElementById('messagesTable');
            
            loading.style.display = 'block';
            table.style.display = 'none';

            const senderNickname = document.getElementById('messageSearch').value;
            const messageType = document.getElementById('messageTypeFilter').value;
            
            let url = `/api/backend/messages?page=${page}&size=${pageSize}`;
            if (senderNickname) url += `&senderNickname=${encodeURIComponent(senderNickname)}`;
            if (messageType) url += `&messageType=${messageType}`;

            fetch(url)
                .then(response => response.json())
                .then(data => {
                    loading.style.display = 'none';
                    
                    if (data.success) {
                        displayMessages(data.data);
                        updateMessagesPagination(data.total, page);
                        table.style.display = 'table';
                    } else {
                        showNotification('加载消息失败: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    showNotification('加载消息失败: ' + error.message, 'error');
                });
        }

        // 显示消息列表
        function displayMessages(messages) {
            const tbody = document.getElementById('messagesTableBody');
            tbody.innerHTML = '';

            messages.forEach(message => {
                const tr = document.createElement('tr');
                const content = message.content.length > 100 ? 
                    message.content.substring(0, 100) + '...' : message.content;
                
                tr.innerHTML = `
                    <td>${message.senderNickname}</td>
                    <td><span class="badge">${getMessageTypeText(message.messageType)}</span></td>
                    <td title="${message.content}">${content}</td>
                    <td>${new Date(message.sendTime).toLocaleString()}</td>
                    <td>
                        <button class="action-btn danger" onclick="deleteMessage(${message.id})">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </td>
                `;
                tbody.appendChild(tr);
            });
        }

        // 获取消息类型文本
        function getMessageTypeText(type) {
            const typeMap = {
                'TEXT': '文本',
                'IMAGE': '图片',
                'SYSTEM': '系统',
                'JOIN': '加入',
                'LEAVE': '离开',
                'AI_ROBOT': '机器人',
                'GIFT': '礼物'
            };
            return typeMap[type] || type;
        }

        // 搜索消息
        function searchMessages() {
            loadMessages(0);
        }

        // 删除消息
        function deleteMessage(messageId) {
            if (!confirm('确定要删除这条消息吗？此操作不可恢复！')) {
                return;
            }

            fetch(`/api/backend/messages/${messageId}`, {
                method: 'DELETE'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showNotification(data.message, 'success');
                        loadMessages(currentMessagesPage);
                        loadStats();
                    } else {
                        showNotification(data.message, 'error');
                    }
                })
                .catch(error => {
                    showNotification('删除失败: ' + error.message, 'error');
                });
        }

        // 更新消息分页
        function updateMessagesPagination(total, currentPage) {
            const pagination = document.getElementById('messagesPagination');
            const totalPages = Math.ceil(total / pageSize);
            
            if (totalPages <= 1) {
                pagination.style.display = 'none';
                return;
            }
            
            pagination.style.display = 'flex';
            pagination.innerHTML = `
                <button ${currentPage === 0 ? 'disabled' : ''} onclick="loadMessages(${currentPage - 1})">
                    <i class="fas fa-chevron-left"></i> 上一页
                </button>
                <span>第 ${currentPage + 1} 页 / 共 ${totalPages} 页</span>
                <button ${currentPage >= totalPages - 1 ? 'disabled' : ''} onclick="loadMessages(${currentPage + 1})">
                    下一页 <i class="fas fa-chevron-right"></i>
                </button>
            `;
        }

        // 显示通知
        function showNotification(message, type = 'success') {
            const notification = document.createElement('div');
            notification.className = `notification ${type}`;
            notification.textContent = message;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.classList.add('show');
            }, 100);
            
            setTimeout(() => {
                notification.classList.remove('show');
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 300);
            }, 3000);
        }

        // 禁言管理相关函数
        
        // 显示禁言用户（从快捷入口调用）
        function showBannedUsers() {
            // 切换到禁言管理选项卡
            document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
            
            document.querySelector('[data-tab="banned"]').classList.add('active');
            document.getElementById('banned').classList.add('active');
            
            loadBannedUsers();
        }

        // 加载被禁言用户列表
        function loadBannedUsers() {
            const loading = document.getElementById('bannedUsersLoading');
            const table = document.getElementById('bannedUsersTable');
            const noUsers = document.getElementById('noBannedUsers');
            const tbody = document.getElementById('bannedUsersTableBody');

            loading.style.display = 'block';
            table.style.display = 'none';
            noUsers.style.display = 'none';

            // 使用管理员会话ID（这里简化处理，实际应该从登录信息获取）
            fetch('/api/admin/banned-users?adminSessionId=admin-session-id')
                .then(response => response.json())
                .then(data => {
                    loading.style.display = 'none';
                    
                    if (data.success) {
                        const users = data.data || [];
                        
                        if (users.length === 0) {
                            noUsers.style.display = 'block';
                            // 更新禁言用户数量统计
                            document.getElementById('bannedUsersCount').textContent = '0';
                        } else {
                            table.style.display = 'table';
                            tbody.innerHTML = users.map(user => {
                                // 格式化时间函数，去掉T字符
                                const formatDateTime = (dateStr) => {
                                    if (!dateStr) return '-';
                                    const date = new Date(dateStr);
                                    return date.getFullYear() + '-' + 
                                           String(date.getMonth() + 1).padStart(2, '0') + '-' +
                                           String(date.getDate()).padStart(2, '0') + ' ' +
                                           String(date.getHours()).padStart(2, '0') + ':' +
                                           String(date.getMinutes()).padStart(2, '0') + ':' +
                                           String(date.getSeconds()).padStart(2, '0');
                                };
                                
                                const banExpireTime = user.banExpireTime ? formatDateTime(user.banExpireTime) : '永久';
                                const createTime = user.createTime ? formatDateTime(user.createTime) : '-';
                                const isExpired = user.banExpireTime && new Date(user.banExpireTime) < new Date();
                                
                                return `
                                    <tr>
                                        <td>${user.nickname}</td>
                                        <td>${user.banReason || '未指定'}</td>
                                        <td>${createTime}</td>
                                        <td>${banExpireTime}</td>
                                        <td>
                                            <span class="badge ${isExpired ? 'badge-warning' : 'badge-danger'}">
                                                ${isExpired ? '已过期' : '禁言中'}
                                            </span>
                                        </td>
                                        <td>
                                            <button class="btn btn-sm btn-success" onclick="unbanUser('${user.sessionId}', '${user.nickname}')">
                                                解除禁言
                                            </button>
                                        </td>
                                    </tr>
                                `;
                            }).join('');
                            
                            // 更新禁言用户数量统计
                            document.getElementById('bannedUsersCount').textContent = users.length.toString();
                        }
                    } else {
                        showNotification('加载禁言用户列表失败：' + data.message, 'error');
                        noUsers.style.display = 'block';
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    console.error('加载禁言用户列表失败:', error);
                    showNotification('加载禁言用户列表失败：' + error.message, 'error');
                    noUsers.style.display = 'block';
                });
        }

        // 搜索被禁言用户
        function searchBannedUsers() {
            const searchTerm = document.getElementById('bannedUserSearch').value.trim();
            // 这里可以实现搜索逻辑，暂时直接重新加载
            loadBannedUsers();
        }

        // 解除用户禁言
        function unbanUser(sessionId, nickname) {
            if (!confirm(`确定要解除用户 "${nickname}" 的禁言吗？`)) {
                return;
            }

            const requestData = {
                adminSessionId: 'admin-session-id', // 实际应该从登录信息获取
                targetSessionId: sessionId
            };

            fetch('/api/admin/unban-user', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification(data.message, 'success');
                    loadBannedUsers(); // 重新加载列表
                    loadStats(); // 更新统计信息
                } else {
                    showNotification(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('解除禁言失败:', error);
                showNotification('解除禁言失败：' + error.message, 'error');
            });
        }

        // 在用户管理中添加禁言功能（修改现有的用户操作）
        function banUser(sessionId, nickname) {
            const reason = prompt(`请输入禁言用户 "${nickname}" 的原因:`, '违规行为');
            if (reason === null) return; // 用户取消

            const hours = prompt('请输入禁言时长（小时，留空为永久禁言）:', '24');
            let banHours = null;
            if (hours && hours.trim() !== '') {
                banHours = parseInt(hours);
                if (isNaN(banHours) || banHours <= 0) {
                    alert('禁言时长必须是正整数');
                    return;
                }
            }

            const requestData = {
                adminSessionId: 'admin-session-id', // 实际应该从登录信息获取
                targetSessionId: sessionId,
                reason: reason.trim(),
                banHours: banHours
            };

            fetch('/api/admin/ban-user', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification(data.message, 'success');
                    loadUsers(); // 重新加载用户列表
                    loadBannedUsers(); // 重新加载禁言用户列表
                    loadStats(); // 更新统计信息
                } else {
                    showNotification(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('禁言用户失败:', error);
                showNotification('禁言用户失败：' + error.message, 'error');
            });
        }

        // 初始化时加载禁言用户数量
        function loadStats() {
            fetch('/api/backend/stats')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const stats = data.data;
                        document.getElementById('totalUsers').textContent = stats.totalUsers;
                        document.getElementById('onlineUsers').textContent = stats.onlineUsers;
                        document.getElementById('totalMessages').textContent = stats.totalMessages;
                        document.getElementById('todayMessages').textContent = stats.todayMessages;
                        document.getElementById('adminCount').textContent = stats.adminCount;
                    }
                })
                .catch(error => {
                    console.error('加载统计信息失败:', error);
                });
            
            // 同时加载禁言用户数量
            fetch('/api/admin/banned-users?adminSessionId=admin-session-id')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const bannedCount = data.data ? data.data.length : 0;
                        document.getElementById('bannedUsersCount').textContent = bannedCount.toString();
                    }
                })
                .catch(error => {
                    console.error('加载禁言用户数量失败:', error);
                    document.getElementById('bannedUsersCount').textContent = '-';
                });
        }
    </script>
</body>
</html> 